$(() => {
    init();
});

function init() {
    isRememberMe();
    $(".login-button-box button").click(submit);
}

/* 请求Remember状态 */
function isRememberMe() {
    $.ajax({
        url: "/api/back/admin/rememberMe", type: "GET", xhrFields: {
            withCredentials: true
        }, success: (ret) => {
            if (ret.code === 0) {
                let data = ret.data;
                loginForm.username.value = data.code;
                loginForm.password.value = data.password;
            }
        }
    });
}

function submit() {
    let username = loginForm.username.value;
    let password = loginForm.password.value;
    let verifyCode = loginForm.verifyCode.value;
    let isRememberMe = $("input[name='rememberMe']")[0].checked;
    if (username === "" || password === "") {
        alert("请输入正确的账号及密码!");
        return;
    } else if (verifyCode === "") {
        alert("请输入验证码!");
        return;
    }
    $.ajax({
        url: "/api/back/admin/login", type: "GET", xhrFields: {
            withCredentials: true
        }, data: {
            "username": username,
            "password": password,
            "verifyCode": verifyCode,
            "isRememberMe": isRememberMe
        }, success: (ret) => {
            if (ret.code === 0) {
                $.cookie("loginToken", ret.data.loginToken, {expires: 1, path: "/"});
                window.location.href = "/";
            } else {
                alert(ret.msg);
                loginForm.reset();
            }
        }
    });
}